<template>
  <div class="channel-edit">
    <!-- 当前登陆用户已经订阅的频道 -->
    <div class="channel">
      <van-cell
        title="我的频道"
        :border="false"
        @click="isEditing = !isEditing"
      >
        <van-button size="mini" type="info">{{
          isEditing ? "取消" : "编辑"
        }}</van-button>
      </van-cell>
      <van-grid>
        <van-grid-item
          v-for="(item, index) in channelList"
          :key="item.id"
          @click="hChangeChannel(index)"
          :class="{ red: index === curIndex }"
        >
          <span>{{ item.name }}</span>
          <van-icon
            name="cross"
            class="btn"
            v-if="isEditing && item.id != 0"
          ></van-icon>
        </van-grid-item>
      </van-grid>
    </div>
    <!-- 当前登陆用户没有订阅的频道 -->
    <div class="channel">
      <van-cell title="可选频道" :border="false"></van-cell>
      <van-grid>
        <van-grid-item
          v-for="index in recommendChannels"
          :key="index.id"
          @click="hAddChannel(index)"
        >
          <span>{{ index.name }}</span>
        </van-grid-item>
      </van-grid>
    </div>
  </div>
</template>

<script>
import { arrSub } from '@/utils/index.js'
import { getAllChannels, addChannels, delChannel } from '@/api/channel.js'
export default {
  name: 'ChannelEdit',
  props: ['channelList', 'curIndex'],
  data () {
    return {
      isEditing: false,
      allChannels: []
    }
  },
  created () {
    this.loadAllChannels()
  },
  methods: {
    async doDelete (index) {
      const channelId = this.channelList[index].id
      try {
        const res = await delChannel(channelId)
        console.log(res)
        this.channelList.splice(index, 1)
        if (index < this.curIndex) {
          this.$emit('update-active')
        }
        this.$toast.success('真的不要了？')
      } catch (err) {
        console.log(err)
      }
    },
    async hAddChannel (index) {
      try {
        const res = await addChannels([index])
        console.log(index)
        console.log(res)
        this.channelList.push(index)
      } catch (err) {
        console.log(err)
      }
    },
    async loadAllChannels () {
      try {
        const res = await getAllChannels()
        console.log(res)
        this.allChannels = res.data.data.channels
      } catch (err) {
        console.log(err)
      }
    },
    hChangeChannel (index) {
      console.log(index)
      if (this.isEditing) {
        this.doDelete(index)
      } else {
        this.$emit('change-channel', index)
      }
    }
  },
  computed: {
    // 计算属性
    recommendChannels () {
      console.log('计算属性....')
      return arrSub(this.allChannels, this.channelList)
    }
  }
}
</script>

<style lang="less" scoped>
.channel {
  padding: 15px;
  font-size: 14px;
}
.btn {
  position: absolute;
  top: 0;
  right: 0;
  font-size: 10px;
}
// 高亮显示
.red {
  color: red;
  font-weight: bold;
}
</style>
